﻿Imports System.Text

Namespace DbConnection.Impl

    ''' <summary>
    ''' This connection will write raise an error if the query contains quotes
    ''' </summary>
    Public Class QuoteRaisingConnection
        Implements IConnection

        Private _delegate As IConnection


        Public Sub close() Implements IConnection.close
            Me._delegate.close()
        End Sub

        Public Function executeNonQuery(ByVal query As String, ByVal ParamArray parameters() As System.Data.SqlClient.SqlParameter) As Integer Implements IConnection.executeNonQuery
            CheckQuery(query)
            Return Me._delegate.executeNonQuery(query, parameters)
        End Function

        Public Function executeQuery(ByVal query As String, ByVal ParamArray parameters() As System.Data.SqlClient.SqlParameter) As System.Data.DataTable Implements IConnection.executeQuery
            CheckQuery(query)
            Return Me._delegate.executeQuery(query, parameters)
        End Function

        Public Function executeScalar(ByVal query As String, ByVal ParamArray parameters() As System.Data.SqlClient.SqlParameter) As Object Implements IConnection.executeScalar
            CheckQuery(query)
            Return Me._delegate.executeScalar(query, parameters)
        End Function

        Public Function executeFileScript(ByVal filePath As String) As Integer Implements IConnection.executeFileScript
            Return Me._delegate.executeFileScript(filePath)
        End Function

        ''' <summary>
        ''' Checks a query string for illegal characters (') and raise an error if it find one
        ''' </summary>
        ''' <param name="query">Query to check</param>
        ''' <remarks>This check catches a super set of queries that may be open to SQL injection.  However,
        ''' it will also catch queries that are open to SQL injection.
        ''' It additionally catches:
        ''' * Queries where the developer has included a quoted string, but no string is built up inside it (that the user could interfere with)
        ''' * Queries containing correctly escaped quotes inside text.
        ''' </remarks>
        Public Sub CheckQuery(ByVal query As String)

            Dim validQuery As Boolean = query Is Nothing OrElse Not query.Contains("'")

            ' Does it contain a single quote
            If Not validQuery Then
                Throw New Exception(query + " contains quotes")
            End If


        End Sub


        Public Sub setDecorated(ByVal o As IConnection)
            _delegate = o
        End Sub
    End Class

End Namespace
